let url = "/api/v1/cd/fromData/"
// #ifdef APP-PLUS
url = "http://wl.antaigroup.com:8795/api/v1/cd/fromData/"
// #endif
export const getAppFormData = (id, callback) => {
	uni.request({
		url: url + id,
		method: 'GET',
		success: (res) => {
			if (res.data.status == 'succeed') {
				const data = res.data.data
				if (data && data.form_data_json) {
					const json = JSON.parse(data.form_data_json)
					const rulesJsonOld = JSON.parse(data.rulesJson)
					const rulesJson = rulesJsonOld
					const formListOld = json[0].list
					disposeRules(rulesJsonOld, data => {
						const rulesJson = data
						const formList = disposeFormList(formListOld)
						callback.call(undefined, {
							formList,
							rulesJson
						})
					})
				} else {}
			}
		},
		fail: (err) => {
			console.log(err, 'err')
		}
	})
};
const disposeRules = (options, callback) => {
	// console.log('options: ', options);
	let ruleMap = {}
	let ruleKeys = Object.keys(options)
	ruleKeys.forEach((key) => {
		ruleMap[key] = {
			"rules": []
		}
		let ruleKeyMap = options[key]
		if (ruleKeyMap.required) {
			ruleMap[key]['rules'].push({
				required: true,
				errorMessage: `${ruleKeyMap.label}为必填项!`
			})
		}
		if (ruleKeyMap.customObj) {
			ruleMap[key]['rules'].push({
				validateFunction: function(rule, value, data, callback) {
					if (!data[ruleKeyMap.customObj]) {
						callback(ruleKeyMap.customErr)
					}
					callback(ruleKeyMap.customErr)
					return true
				}
			})
		}
		if (ruleKeyMap.regList) {
			ruleKeyMap.regList.forEach((e) => {
				ruleMap[key]['rules'].push({
					validateFunction: function(rule, value, data, callback) {
						if (!eval(e.pattern).test(value)) {
							callback(e.message)
						}
						return true
					}
				})
			})
		}
	})
	callback.call(undefined, ruleMap)
}

const disposeFormList = (options) => {
	let formList = []
	options.forEach((item) => {
		if (item[item.type] && item[item.type].customObj) {
			let map = {}
			map.prop = item[item.type].customObj
			map.type = 'custom'
			map.custom = {}
			formList.push(map)
		}
		formList.push(item)

	})
	return formList;
}